<template>
  <div id="addPicturePage">
    <a-typography-paragraph v-if="spaceId" type="secondary">
      保存至空间：<a :href="`/space/${spaceId}`" target="_blank">{{ spaceId }}</a>
    </a-typography-paragraph>

    <a-tabs v-model:activeKey="activeKey">
      <a-tab-pane key="file" tab="文件上传">
        <!-- 图片上传组件 -->
        <div class="upload-section">
          <h3>{{ route.query?.id ? '修改图片' : '添加图片' }}</h3>
          <PictureUpload :picture="picture" :spaceId="spaceId" @success="onSuccess"></PictureUpload>
        </div>
      </a-tab-pane>
      <a-tab-pane key="url" tab="URL上传" force-render>
        <UrlPictureUpload
          :picture="picture"
          :spaceId="spaceId"
          @success="onSuccess"
        ></UrlPictureUpload>
      </a-tab-pane>
    </a-tabs>

    <div v-if="picture" class="edit-bar">
      <a-button :icon="h(EditOutlined)" @click="doEditPicture">编辑图片</a-button>
      <a-button type="primary" ghost :icon="h(FullscreenOutlined)" @click="doImagePainting">
        AI 扩图
      </a-button>
      <!-- 注意:imageUrl访问腾讯云的网址会存在跨域问题,出现的话记得在腾讯云中对应的存储中添加跨域配置
      https://console.cloud.tencent.com/cos/bucket-->
      <ImageCropper
        ref="imageCropperRef"
        :imageUrl="picture?.host + picture?.originalUrl"
        :picture="picture"
        :spaceId="spaceId"
        :space="space"
        :onSuccess="onCropSuccess"
      />
      <!--AI扩图组件-->
      <ImageOutPainting
        ref="imageOutPaintingRef"
        :picture="picture"
        :spaceId="spaceId"
        :onSuccess="onImageOutPaintingSuccess"
      />
    </div>

    <!-- 图片信息表单 -->
    <div v-if="picture" class="form-section">
      <a-form
        layout="vertical"
        ref="formRef"
        name="pictureForm"
        :model="pictureForm"
        @finish="handleSubmit"
      >
        <a-form-item name="name" label="名称">
          <a-input v-model:value="pictureForm.name" placeholder="请输入名称" allowClear />
        </a-form-item>
        <a-form-item name="introduction" label="简介">
          <a-textarea
            v-model:value="pictureForm.introduction"
            placeholder="请输入简介"
            :auto-size="{ minRows: 2, maxRows: 8 }"
            allowClear
          />
        </a-form-item>
        <a-form-item name="category" label="分类">
          <a-auto-complete
            v-model:value="pictureForm.category"
            placeholder="请输入分类"
            :options="categoryOptions"
            allowClear
          />
        </a-form-item>
        <a-form-item name="tags" label="标签">
          <a-select
            v-model:value="pictureForm.tags"
            placeholder="请选择或输入标签"
            mode="tags"
            :options="tagsOptions"
            allowClear
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" style="width: 100%" :loading="submitting">
            {{ route.query?.id ? '修改' : '创建' }}
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import PictureUpload from '@/components/PictureUpload.vue'
import { computed, h, onMounted, reactive, ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { EditOutlined, FullscreenOutlined } from '@ant-design/icons-vue'
import {
  editPictureUsingPost,
  getPictureVoByIdUsingGet,
  listPictureTagCategoryUsingGet,
} from '@/api/pictureController.ts'
import { useRoute, useRouter } from 'vue-router'
import UrlPictureUpload from '@/components/UrlPictureUpload.vue'
import ImageCropper from '@/components/ImageCropper.vue'
import ImageOutPainting from '@/components/ImageOutPainting.vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'

const activeKey = ref<'file' | 'url'>('file')

// 定义图片对象引用
const picture = ref<API.PictureVO | null>(null)

// 成功上传图片后的回调函数
/**
 * 当图片上传成功时被调用。
 * 更新 `picture` 变量，并将新图片的名称同步到表单中。
 */
const onSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
  pictureForm.name = newPicture.name
}

// 表单数据模型
const pictureForm = reactive<API.PictureEditRequest>({
  name: '',
  introduction: '',
  category: '',
  tags: [],
})

// 获取路由和路由器实例
const router = useRouter()
const route = useRoute()

// 提交状态标记
const submitting = ref(false)
// 空间 id
const spaceId = computed(() => {
  return route.query?.spaceId
})

// FORM finish	提交表单且数据验证成功后回调事件	function(values)
/**
 * 处理表单提交逻辑。
 * 如果是修改操作，则根据提供的 ID 修改现有图片信息；
 * 如果是创建操作，则上传新图片信息。
 */
const handleSubmit = async (values) => {
  console.log('handleSubmit', values)
  if (submitting.value) return
  submitting.value = true
  try {
    const pictureId = picture.value?.id
    if (!pictureId) {
      return
    }
    // 注意这里是修改图片的信息，比如添加图片的标签之类的。上传其实在上传组件中已经完成同时存入了数据库，所以这里要给id
    const res = await editPictureUsingPost({
      id: pictureId,
      spaceId: spaceId.value,
      ...values,
    })
    if (res.code === 0 && res.data) {
      message.success(`${route.query?.id ? '修改' : '创建'}成功`)
      // 跳转到图片详情页
      await router.push({
        path: `/picture/${pictureId}`,
      })
    } else {
      message.error(`失败: ${res.message || '未知错误'}`)
    }
  } catch (error) {
    message.error('提交失败')
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 分类和标签选项列表
const tagsOptions = ref<{ label: string; value: string }[]>([])
const categoryOptions = ref<{ label: string; value: string }[]>([])

/**
 * 获取所有可用的分类和标签选项。
 * 这些选项用于填充分类选择框和标签选择框。
 */
const fetchCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.code === 0 && res.data) {
    tagsOptions.value = res.data.tagList.map((item: string) => ({ label: item, value: item }))
    categoryOptions.value = res.data.categoryList.map((item: string) => ({
      label: item,
      value: item,
    }))
  }
}

onMounted(() => {
  fetchCategoryOptions()
})

/**
 * 获取旧图片信息。
 * 如果路由中有 `id` 参数，则尝试加载对应 ID 的图片信息并填充表单。
 */
const getOldPicture = async () => {
  const id = route.query?.id
  if (id) {
    const res = await getPictureVoByIdUsingGet({ id: id.toString() })
    if (res.code === 0 && res.data) {
      const data = res.data
      picture.value = data
      Object.assign(pictureForm, {
        name: data.name,
        introduction: data.introduction,
        category: data.category,
        tags: data.tags,
      })
    }
  }
}

onMounted(async () => {
  await getOldPicture()
})

// 图片编辑弹窗引用
const imageCropperRef = ref()

// 编辑图片
const doEditPicture = () => {
  if (imageCropperRef.value) {
    imageCropperRef.value.openModal()
  }
}

// 编辑成功事件
const onCropSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

// AI 扩图弹窗引用
const imageOutPaintingRef = ref()

// AI 扩图
const doImagePainting = () => {
  if (imageOutPaintingRef.value) {
    imageOutPaintingRef.value.openModal()
  }
}

// 编辑成功事件
const onImageOutPaintingSuccess = (newPicture: API.PictureVO) => {
  picture.value = newPicture
}

const space = ref<API.SpaceVO>()

// 获取空间信息
const fetchSpace = async () => {
  // 获取数据
  if (spaceId.value) {
    const res = await getSpaceVoByIdUsingGet({
      id: spaceId.value,
    })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    }
  }
}

watchEffect(() => {
  fetchSpace()
})
</script>

<style scoped>
/* 页面布局 */
#addPicturePage {
  max-width: 720px;
  margin: 0 auto;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

/* 上传区段样式 */
.upload-section {
  margin-bottom: 24px;
}

.upload-section h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #333;
}

/* 表单区段样式 */
.form-section {
  margin-bottom: 24px;
}

.form-section h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #333;
}

/* 表单项样式 */
.ant-form-item {
  margin-bottom: 16px;
}

/* 提交按钮样式 */
.ant-btn-primary {
  height: 40px;
  font-size: 16px;
}

/* 文本域最小行数调整 */
.ant-input < textarea > {
  min-height: 64px;
}

#addPicturePage .edit-bar {
  text-align: center;
  margin: 16px 0;
}
</style>
